package uvsq.acsis.projects.xml.util;

import java.io.File;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



public class QueryHelper {

	@SuppressWarnings("unchecked")
	private static <T> T xPathQuery(String xPath, String filePath, QName qName){
		
		XPathFactory xpathFact = XPathFactory.newInstance();
		XPath path = xpathFact.newXPath();
		
		try {
			
			XPathExpression xExpression = path.compile(xPath); //"//book[@isbn=0140177280]");
			
			return (T) xExpression.evaluate(XmlHelper.getDocument(new File(filePath)), qName);
			
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	public static Node xPathAsNode(String xPath, String filePath){
		return xPathQuery(xPath, filePath, XPathConstants.NODE);
	}
	
	public static String xPathAsNodeString(String xPath, String filePath){
		return XmlHelper.nodeToString(xPathAsNode(xPath, filePath));
	}
	
	public static NodeList xPathAsNodeList(String xPath, String filePath){
		return xPathQuery(xPath, filePath, XPathConstants.NODESET);
	}
	
	public static String xPathAsNodeListString(String xPath, String filePath){
		return XmlHelper.nodeToString(xPathAsNodeList(xPath, filePath));
	}
}
